#include <iostream>
#include<cstdio>
#include <unistd.h>
#include<sys/types.h>
#include<cstring>
#include<sys/wait.h>

void ChildWrite(int wfd)
{
    char c = 0;
    int cnt =0;
    while(1)
    {
        //snprintf(buffer,sizeof(buffer),"I am child,pid:%d,cnt:%d",getpid(),cnt++);
        write(wfd,&c,1);
        printf("child:%d\n",cnt++);
        //sleep(3);
    } 
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer)-1);
        //预留一个空间

        if(n>0)
        {
            buffer[n]=0;
            std::cout<<"child say :"<<buffer<<std::endl;
        }
        else if(n==0)
        {
            std::cout<<"n : "<<n<<std::endl;
            std::cout<<"子进程退出，我父进程也退出"<<std::endl;
            break;
        }
        else
        {
            break;
        }

        break; 
    }
}

int main()
{
    // 1.创建管道
    int fds[2] = {0}; //fds[0]:读端 fds[1]：写端
    int n = pipe(fds);

    if (n < 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    std::cout << "fds[0]:" << fds[0] << std::endl;
    std::cout << "fds[1]:" << fds[1] << std::endl;

    // 2.创建子进程
    pid_t id = fork();
    if (id==0)//子进程
    {
        //code
        //f->r ,c->w
        close(fds[0]);
        ChildWrite(fds[1]);

        close(fds[1]);
        exit(0);
    }

    //3.关闭不需要的读写段，形成通信信道
    //f->r ,c->w
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);

    int 
    waitpid(id,nullptr,0);

 
    return 0;
}